#include "CloudClient.h"
#include "ui_CloudClient.h"

CloudClient::CloudClient(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::CloudClient)
{
    ui->setupUi(this);
    loadConfigFile();

    connect(&m_tcpSocket, SIGNAL(connected()), this, SLOT(connectSuccess()));
    connect(&m_tcpSocket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(connectError(QAbstractSocket::SocketError)));

    /*创建socket, 连接服务器*/
    m_tcpSocket.connectToHost(QHostAddress(m_strIP), m_Port);

}

CloudClient::~CloudClient()
{
    delete ui;
}

void CloudClient::loadConfigFile()
{
    QFile file(":/client.cfg");
    if(file.open(QIODevice::ReadOnly)){
        QByteArray data = file.readAll();
        QString strData = data;
        strData.replace("\n", " ");
        QStringList strList = strData.split(" ");
        m_strIP = strList[0];
        m_Port = strList[1].toInt();

        qDebug() << m_strIP << ":" << m_Port;
    }

}

void CloudClient::connectSuccess()
{
    QMessageBox::information(this, "连接服务器", "连接服务器成功");
}

void CloudClient::connectError(QAbstractSocket::SocketError)
{
    QMessageBox::warning(this, "连接服务器", "连接服务器失败");
}

void CloudClient::on_pushButton_clicked()
{
    QString strmsg = ui->lineEdit->text();
    qDebug() << "strmsg:" << strmsg;

    if(!strmsg.isEmpty()){
        PDU *pdu = mkPDU(0);
        // pdu->usPDULen = sizeof(PDU); // 在mkPDU中已经指定，所以在这里不需要了
        pdu->usPDUType = 1234;
        memcpy(pdu->usData, strmsg.toStdString().c_str(), strmsg.size());
        m_tcpSocket.write((char*)pdu, pdu->usPDULen);

        free(pdu);
        pdu = NULL;
    }else{
        qDebug() << "lineEdit is empty";
    }
}

